<script setup>
import { ref, reactive, toRefs, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import {useRoute}   from "vue-router";
import server from "../utils/request.js";
import {getUserIdFromToken} from "../utils/jwtUtil.js"
//根据登录的token信息拿到登录的id,根据id拿到数据
const userId = getUserIdFromToken();

// 表单数据
const formData = ref({
  id: '',
  username: '',
  name: '',
  image: '',
  phone: '',
  intro: '',
  status: 1
})

// 表单验证规则
const formRules = reactive({
  name: [
    { required: true, message: '请输入商户名', trigger: 'blur' },
    { min: 2, max: 50, message: '商户名长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  intro: [
    { max: 500, message: '商家描述不能超过500个字符', trigger: 'blur' }
  ]
})

// 上传相关配置
const uploadUrl = 'http://localhost:8080/merchant/upload' // 实际项目中替换为真实上传接口

// 这里使用了表单验证，实际项目中需要根据需要调整
const merchantForm = ref(null)
// 保存商家信息
const saveMerchant = async () => {
  if (!merchantForm.value) {
    ElMessage.error('表单实例未找到');
    return;
  }
  try {
    // 调用表单验证（Promise 形式）
    await merchantForm.value.validate();
    // 验证通过后提交
    const { data } = await server.put(`/merchant/`, formData.value);
    if (data.code === 200) {
      ElMessage.success('保存成功');
    } else {
      ElMessage.error(`保存失败：${data.msg}`);
    }
  } catch (error) {
    // 验证失败会进入这里（无需额外处理，表单会自动提示错误）
    console.log('表单验证失败', error);
  }
};

// 图片上传成功处理
const handleImageUpload = (response) => {
  console.log(response)
  // 假设上传接口返回格式为 { url: '图片地址' }
  formData.value.image = response.data
  console.log(formData.value.image)
  ElMessage.success('图片上传成功')
}

// 图片上传前验证
const beforeImageUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJpgOrPng) {
    ElMessage.error('只能上传JPG/PNG格式的图片')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB')
    return false
  }
  return true
}

// 模拟获取商家详情数据
const fetchMerchantDetail = async () => {
  try {
    let {data:data} = await server.get(`merchant/${userId}`)
    Object.assign(formData.value,data.data)
  } catch (error) {
    ElMessage.error('获取商家详情失败')
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchMerchantDetail()
})
</script>
<template>
  <el-card  class="page-card">
    <div slot="header" class="card-header">
      <span>编辑商家</span>
      <div class="button-group">
        <el-button
            size="small"
        >
          取消
        </el-button>
        <el-button
            type="primary"
            size="small"
            @click="saveMerchant"
        >
          保存
        </el-button>
      </div>
    </div>

    <el-form
        ref="merchantForm"
        :model="formData.value"
        :rules="formRules"
        label-width="120px"
        class="merchant-form"
    >
      <el-form-item label="商家ID" prop="id">
        <el-input v-model="formData.id" disabled></el-input>
      </el-form-item>

      <el-form-item label="商家账号" prop="username">
        <el-input v-model="formData.username" disabled></el-input>
      </el-form-item>

      <el-form-item label="商户名" prop="name">
        <el-input v-model="formData.name"></el-input>
      </el-form-item>

      <el-form-item label="商家照片" prop="image">
        <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleImageUpload"
            :before-upload="beforeImageUpload"
        >
          <el-image
              v-if="formData.image"
              :src="formData.image"
              style="width: 200px; height: 150px; object-fit: contain"
          ></el-image>
          <div v-else class="upload-placeholder">
            <el-icon><Plus /></el-icon>
            <div class="upload-text">点击上传</div>
          </div>
        </el-upload>
      </el-form-item>

      <el-form-item label="手机号" prop="phone">
        <el-input v-model="formData.phone" placeholder="请输入手机号"></el-input>
      </el-form-item>

      <el-form-item label="商家描述" prop="intro">
        <el-input
            v-model="formData.intro"
            type="textarea"
            placeholder="请输入商家描述"
        ></el-input>
      </el-form-item>
      <el-form-item label="经度" prop="phone">
        <el-input v-model="formData.longitude" placeholder="请输入经度"></el-input>
      </el-form-item>
      <el-form-item label="经度" prop="phone">
        <el-input v-model="formData.latitude" placeholder="请输入纬度"></el-input>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<style scoped>
.merchant-page {
  padding: 20px;
}

.page-card {
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.edit-btn {
  margin-left: auto;
}

.button-group {
  display: flex;
  gap: 10px;
}

.merchant-form {
  margin-top: 20px;
}

.avatar-uploader {
  display: inline-block;
}

.upload-placeholder {
  width: 200px;
  height: 150px;
  border: 1px dashed #ccc;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.upload-text {
  margin-top: 8px;
  color: #666;
  font-size: 14px;
}
</style>